<template>
	<view class="study-container">
		<!-- 顶部标题 -->
		<view class="header">
			<template v-if="showListType !== 'root'">
				<view
					class="back"
					@tap="goBack">
					<image
						src="/static/images/left-arrow.png"
						style="width: 18rpx; height: 36rpx" />
				</view>
			</template>
			<view class="title">{{ '爱德思ALevel资料站' }}</view>
		</view>

		<!-- 搜索框 -->
		<view
			class="search-box"
			v-if="false">
			<image
				class="search-icon"
				src="/static/images/search.png"
				mode="aspectFit" />
			<input
				type="text"
				v-model="searchQuery"
				placeholder="输入搜索内容"
				@input="handleSearch" />
		</view>

		<view class="all-content">
			<!-- 卡片视图 -->
			<view
				v-if="currentLevel <= 2"
				class="card-section">
				<topic
					:list="showList"
					@click="goOn"
					:type="type" />
			</view>

			<view
				v-else
				class="folder-list">
				<template
					v-for="item in showList"
					:key="item.id">
					<!-- 文件夹视图 -->
					<view
						v-if="item.type === 'folder'"
						class="folder"
						@tap="goOn(item)">
						<image
							class="icon"
							:src="'/static/images/folder1.png'" />
						<view class="content">
							<view class="name">{{ item.name }}</view>
						</view>
						<view class="enter-btn">
							<image src="/static/images/left-arrow.png" />
						</view>
					</view>

					<view
						class="folder"
						v-else
						@tap="openFile(item)">
						<image
							class="icon"
							src="/static/images/pdf1.png"
							mode="aspectFit" />
						<view class="content">
							<view class="name">{{ item.name }}</view>
						</view>
					</view>
				</template>
			</view>
		</view>

		<!-- logo -->
		<view class="logo">
			<image
				src="https://ciyu-edu.oss-cn-beijing.aliyuncs.com/pic/logo.png"
				mode="aspectFit" />

			<view class="logo-text">
				<text>A*俱乐部</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, defineExpose } from 'vue'
import { useUserStore } from '../../stores/user'
import { useFilesStore } from '../../stores/files'
import Topic from './topic.vue'

const filesStore = useFilesStore()
const searchQuery = ref('')
const currentId = ref(null)
const currentLevel = ref(1)
const type = ref('all')
const navigationHistory = ref([null])

// 在页面加载时获取文件树
onMounted(async () => {
	console.log('onMounted Study')
	try {
		// 重置导航状态
		currentId.value = null
		currentLevel.value = 1
		navigationHistory.value = [null]

		// 获取文件树
		await filesStore.fetchFileTree()
	} catch (error) {
		console.error('获取文件树失败:', error)
	}
})

//  findFolderById
const findFolderById = id => {
	// 深度优先搜索
	const stack = [...filesStore.fileTree]
	while (stack.length) {
		const current = stack.pop()
		if (current.id === id) return current
		if (current.children) stack.push(...current.children)
	}
	return null
}
// 计算当前显示的文件列表
const showList = computed(() => {
	let res = []
	if (!currentId.value) {
		res = filesStore.fileTree.filter(item =>
			item.name.includes(searchQuery.value)
		) // 如果是根目录，显示整个文件树
	} else {
		res = findFolderById(currentId.value).children.filter(item =>
			item.name.includes(searchQuery.value)
		)
	}
	return res
})

// 显示类型：root(根目录)、folder(文件夹)、file(文件)
const showListType = computed(() => {
	if (!currentId.value) return 'root'
	if (showList.value.length === 0) return 'file'
	return showList.value[0]?.type === 'folder' ? 'folder' : 'file'
})

const getTopicType = item => {
	if (item.name.includes('时间表')) {
		return 'calendar'
	}
	if (item.name.includes('真题库')) {
		return 'paper'
	}
	return 'textbook'
}

const goOn = item => {
	console.log(item)
	if (!item.children?.length) {
		openFile(item)
		return
	}

	currentLevel.value += 1
	console.log('item:', item)
	if (currentLevel.value === 2) {
		type.value = getTopicType(item)
	}

	if (item.children?.length === 0) return
	currentId.value = item.id
	navigationHistory.value.push(item.id)
}

// 处理返回
const goBack = () => {
	currentLevel.value -= 1
	if (currentLevel.value === 1) {
		type.value = 'all'
	}
	navigationHistory.value.pop()
	currentId.value = navigationHistory.value[navigationHistory.value.length - 1]
}

// 处理搜索
const handleSearch = () => {
	// 实现搜索逻辑
	console.log(searchQuery.value)
}

// 打开文件
const openFile = async file => {
	const userStore = useUserStore()
	if (!userStore.isLoggedIn && file.is_vip) {
		uni.showModal({
			title: '提示',
			content: '该资料属于VIP专享，请先登录后继续使用',
			showCancel: false,
			success: async function () {
				const loginSuccess = await userStore.login()
				if (loginSuccess) {
					// 登录成功后继续执行原来的操作
					handleOpenFile(file)
				}
			}
		})
		return
	}

	// 原来的打开文件逻辑
	handleOpenFile(file)
}

// 将原来的打开文件逻辑抽离出来
const handleOpenFile = async file => {
	try {
		if (!file.oss_url) {
			throw new Error('File URL not found')
		}

		uni.showLoading({ title: '加载中...', mask: true })

		// 获取文件扩展名
		const fileExt = file.name.split('.').pop() || 'pdf'

		// 构建临时文件路径
		const tempFilePath = `${wx.env.USER_DATA_PATH}/${file.name}`

		// 先下载文件到临时目录
		const { statusCode } = await uni.downloadFile({
			url: file.oss_url,
			filePath: tempFilePath
		})

		console.log('下载状态:', statusCode, '临时路径:', tempFilePath)

		if (statusCode === 200) {
			// #ifdef MP-WEIXIN
			// 在微信小程序中使用 wx.openDocument
			await wx.openDocument({
				filePath: tempFilePath,
				fileType: fileExt,
				showMenu: true,
				success: () => {
					// 文档打开成功后，设置导航栏标题
					uni.setNavigationBarTitle({
						title: file.name
					})
				}
			})
			// #endif

			// #ifndef MP-WEIXIN
			await uni.openDocument({
				filePath: tempFilePath,
				fileType: file.mime_type?.split('/')[1] || fileExt,
				showMenu: true
			})
			// #endif
		} else {
			throw new Error(`Download failed with status: ${statusCode}`)
		}
	} catch (error) {
		console.error('预览失败:', error)
		uni.showToast({
			title: '预览失败',
			icon: 'none',
			duration: 2000
		})
	} finally {
		uni.hideLoading()
	}
}

// 下载文件
const downloadFile = async file => {
	const tmpUrl =
		'https://ciyu-edu.oss-cn-beijing.aliyuncs.com/uploads/1741090826442-demo.pdf'
	try {
		if (!file.oss_url) {
			throw new Error('File URL not found')
		}

		uni.showLoading({ title: '下载中...', mask: true })

		const { statusCode, tempFilePath } = await uni.downloadFile({
			url: tmpUrl || file.oss_url
		})

		console.log(statusCode, tempFilePath)

		if (statusCode === 200) {
			const { savedFilePath } = await uni.saveFile({
				tempFilePath
			})

			uni.showToast({
				title: '下载成功',
				icon: 'success',
				duration: 2000
			})

			return savedFilePath
		} else {
			throw new Error('Download failed')
		}
	} catch (error) {
		console.error('下载失败：', error)
		uni.showToast({
			title: '下载失败',
			icon: 'none',
			duration: 2000
		})
	} finally {
		uni.hideLoading()
	}
}

// 收藏/取消收藏
const toggleFavorite = file => {
	file.isFavorite = !file.isFavorite
	// 这里可以调用接口保存收藏状态
}

// 处理点击事件
const handleItemClick = item => {
	if (item.type === 'folder') {
		// 处理文件夹点击
		console.log('点击文件夹:', item)
	} else {
		// 处理文件点击
		openFile(item)
	}
}

// 分享给朋友
const onShareAppMessage = () => {
	return {
		title: '爱德思题库',
		path: '/pages/study/study',
		imageUrl: '/static/images/logo.png'
	}
}

// 分享到朋友圈
const onShareTimeline = () => {
	return {
		title: '爱德思题库',
		path: '/pages/study/study',
		imageUrl: '/static/images/logo.png'
	}
}

defineExpose({
	onShareAppMessage,
	onShareTimeline
})
</script>

<style lang="scss" scoped>
.study-container {
	height: 100vh;
	background: linear-gradient(to right, rgb(43,192, 228), rgb(234, 236, 198));
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
}

.header {
	padding: 0 32rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding-top: calc(var(--status-bar-height) + 50rpx);
	padding-bottom: 40rpx;
	height: 66rpx;
	position: relative;
	flex-shrink: 0;
	.back {
		width: 66rpx;
		height: 66rpx;
		height: 66rpx;
		display: flex;
		border-radius: 50%;
		background: #fff;
		align-items: center;
		justify-content: center;
		position: absolute;
		z-index: 100;
		top: 78rpx;
		image {
			width: 18rpx;
			height: 36rpx;
			margin-left: -6rpx;
		}
	}

	.title {
		color: #fff;
		text-align: center;
		font-family: 'PingFang SC';
		font-size: 32rpx;
		font-weight: 500;
		line-height: 1;
		letter-spacing: -0.28px;
		flex: 1;
	}
}

.all-content {
	padding: 0 32rpx;
	padding-bottom: 20rpx;
	flex: 1;
	overflow-y: auto;
}

.logo {
	display: flex;
	flex-direction: column;
	align-items: center;
  padding: 24rpx;
	image {
		width: 180rpx;
		height: 180rpx;
	}
  .logo-text {
		font-size: 36rpx;
		color: #333;
		font-weight: 500;
	}
}

.search-box {
	background: #fff;
	border-radius: 32rpx;
	padding: 20rpx 32rpx;
	margin: 20rpx 0 40rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	display: flex;
	align-items: center;
	gap: 16rpx;

	.search-icon {
		width: 32rpx;
		height: 32rpx;
		margin-top: -4rpx;
		flex-shrink: 0;
	}

	input {
		flex: 1;
		height: 48rpx;
		font-size: 28rpx;
		color: #333;
		&::placeholder {
			color: #999;
		}
	}
}

// 卡片视图样式
.card-section {
	margin-top: 20rpx;
}

.card-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 24rpx;
}

.folder-card {
	position: relative;
	height: 300rpx;
	border-radius: 22rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.74);
	background: linear-gradient(196deg, #ebebed 4.22%, #b3e2f6 89.05%);
	box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(255, 255, 255, 0.81) inset,
		0rpx 8rpx 60rpx 0rpx rgba(165, 177, 205, 0.46);
	backdrop-filter: blur(4rpx);

	.vip-tag {
		position: absolute;
		top: 0;
		left: 0;
		border-radius: 20rpx 0 20rpx 0;
		background: linear-gradient(to bottom, #3bccdd, #5b88e5);
		padding: 8rpx 16rpx;
		display: flex;
		align-items: center;
		gap: 4rpx;

		image {
			width: 24rpx;
			height: 24rpx;
		}

		text {
			font-size: 20rpx;
			color: #ffffff;
		}
	}

	.card-content {
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.card-icon {
			width: 120rpx;
			height: 120rpx;
			margin-top: 80rpx;
			margin-bottom: 20rpx;
		}

		.card-text {
			width: 100%;
			text-align: center;

			.folder-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
			}
		}
	}

	&:active {
		transform: scale(0.98);
		transition: transform 0.2s;
	}
}

// 文件夹视图样式
.folder-list {
	.folder {
		background: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		display: flex;
		align-items: center;

		border: 2rpx solid rgba(255, 255, 255, 0.74);

		background: linear-gradient(
			196deg,
			rgba(235, 235, 237, 0.41) 4.22%,
			rgba(179, 226, 246, 0.41) 89.05%
		);

		box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(255, 255, 255, 0.81) inset,
			0rpx 8rpx 60rpx 0rpx rgba(165, 177, 205, 0.46);
		backdrop-filter: blur(4rpx);

		.icon {
			margin-right: 24rpx;
			min-width: 80rpx;
			height: 80rpx;
			flex: 0 0 80rpx;
		}

		.content {
			flex: 1;
			width: 100%;

			.name {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
				margin-bottom: 8rpx;
				// 文字溢出处理
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2; // 最多显示2行
				-webkit-box-orient: vertical;
				word-break: break-all; // 允许在任意字符间断行
			}

			.size {
				font-size: 24rpx;
				color: #999;
			}
		}

		.enter-btn {
			width: 66rpx;
			height: 66rpx;
			display: flex;
			border-radius: 50%;
			background: #fff;
			align-items: center;
			justify-content: center;

			image {
				width: 18rpx;
				height: 36rpx;
				transform: rotate(180deg);
				margin-left: 8rpx;
			}
		}

		&:active {
			transform: scale(0.98);
			transition: transform 0.2s;
		}
	}
}

// 文件视图样式
.file-list {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 24rpx;
	padding-bottom: env(safe-area-inset-bottom);

	.file {
		position: relative;
		height: 336rpx;
		border-radius: 22rpx;
		overflow: hidden;

		.bg {
			position: absolute;
			width: 340rpx;
			height: 264rpx;
			left: 0;
			z-index: 1;
		}

		.vip-tag {
			position: absolute;
			top: 6rpx;
			left: 4rpx;
			z-index: 3;
			display: flex;
			align-items: center;
			gap: 10rpx;
			padding: 4rpx 12rpx;
			border-radius: 16rpx;

			.vip-tag-icon {
				width: 24rpx;
				height: 24rpx;
			}

			text {
				color: #fff;
				font-size: 20rpx;
				line-height: 1.4;
			}
		}

		.file-name {
			position: absolute;
			width: 100%;
			height: 248rpx;
			left: 0;
			bottom: 0;
			z-index: 2;

			border-radius: 22rpx;
			border: 2rpx solid rgba(255, 255, 255, 0.74);
			background: linear-gradient(196deg, #ebebed 4.22%, #b3e2f6 89.05%);
			box-shadow: 0rpx 8rpx 20rpx 0rpx rgba(255, 255, 255, 0.81) inset,
				0rpx 8rpx 60rpx 0rpx rgba(165, 177, 205, 0.46);

			display: flex;
			align-items: center;
			justify-content: center;

			.text {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				width: 100%;
				text-align: center;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}
		}

		&:active {
			transform: scale(0.98);
			transition: transform 0.1s;
		}
	}
}
</style>
